package cn.edu.sicnu.cardgame.ui

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import cn.edu.sicnu.cardgame.R
import cn.edu.sicnu.cardgame.data.ProfileRepository

class MainActivity : AppCompatActivity() {

    private lateinit var ivAvatar: ImageView
    private lateinit var tvName: TextView
    private lateinit var tvGender: TextView
    private lateinit var tvStudentId: TextView
    private lateinit var tvPhone: TextView
    private lateinit var tvEmail: TextView
    private lateinit var tvHobby: TextView
    private lateinit var tvHighScore: TextView

    private val editLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {
        // Simply refresh UI from repository after edit returns
        bindProfile()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        ivAvatar = findViewById(R.id.ivAvatar)
        tvName = findViewById(R.id.tvName)
        tvGender = findViewById(R.id.tvGender)
        tvStudentId = findViewById(R.id.tvStudentId)
        tvPhone = findViewById(R.id.tvPhone)
        tvEmail = findViewById(R.id.tvEmail)
        tvHobby = findViewById(R.id.tvHobby)
        tvHighScore = findViewById(R.id.tvHighScore)

        findViewById<Button>(R.id.btnEdit).setOnClickListener {
            editLauncher.launch(Intent(this, EditInfoActivity::class.java))
        }
        findViewById<Button>(R.id.btnStart).setOnClickListener {
            startActivity(Intent(this, GameActivity::class.java))
        }

        bindProfile()
    }

    private fun bindProfile() {
        val p = ProfileRepository.profile
        tvName.text = getString(R.string.label_name) + "：" + (p.name.ifEmpty { "-" })
        tvGender.text = getString(R.string.label_gender) + "：" + (p.gender.ifEmpty { "-" })
        tvStudentId.text = getString(R.string.label_student_id) + "：" + (p.studentId.ifEmpty { "-" })
        tvPhone.text = getString(R.string.label_phone) + "：" + (p.phone.ifEmpty { "-" })
        tvEmail.text = getString(R.string.label_email) + "：" + (p.email.ifEmpty { "-" })
        tvHobby.text = getString(R.string.label_hobby) + "：" + (p.hobbies.ifEmpty { "-" })
        tvHighScore.text = getString(R.string.label_high_score) + "：" + p.highScore
        if (p.avatarUri.isNotEmpty()) {
            ivAvatar.setImageURI(android.net.Uri.parse(p.avatarUri))
        }
    }
}

